# 主应用程序
from fastapi import FastAPI, Request, Form, HTTPException, UploadFile, File
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, JSONResponse
import uvicorn
import asyncio
import json
import os
import shutil
from typing import Optional

from config import Config
from database import Database
from ai_service import AIService
from toutiao_service import ToutiaoService

app = FastAPI(title="头条自动发文系统", version="1.0.0")

# 静态文件和模板
app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/static/uploads", StaticFiles(directory="uploads"), name="uploads")
templates = Jinja2Templates(directory="templates")

# 服务实例
db = Database()
ai_service = AIService()
toutiao_service = ToutiaoService()

@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
    """首页"""
    # 获取当前登录账号
    account = db.get_active_account()
    # 获取最近文章
    articles = db.get_articles(limit=10)
    
    return templates.TemplateResponse("index.html", {
        "request": request,
        "account": account,
        "articles": articles
    })

@app.get("/login", response_class=HTMLResponse)
async def login_page(request: Request):
    """登录页面"""
    return templates.TemplateResponse("login.html", {
        "request": request
    })

@app.post("/api/generate-qr")
async def generate_qr():
    """生成登录二维码"""
    try:
        qr_data = toutiao_service.generate_login_qr()
        if qr_data == "ALREADY_LOGGED_IN":
            return {
                "success": True, 
                "already_logged_in": True,
                "message": "检测到已登录状态"
            }
        elif qr_data:
            return {
                "success": True, 
                "already_logged_in": False,
                "qr_data": qr_data
            }
        else:
            return {"success": False, "message": "生成二维码失败"}
    except Exception as e:
        return {"success": False, "message": f"生成二维码失败: {str(e)}"}

@app.post("/api/check-login")
async def check_login():
    """检查登录状态"""
    try:
        result = toutiao_service.check_login_status()
        return result
    except Exception as e:
        return {"success": False, "message": f"检查登录状态失败: {str(e)}"}

@app.get("/api/connection-status")
async def get_connection_status():
    """获取浏览器连接和登录状态"""
    try:
        status = toutiao_service.get_connection_status()
        
        # 如果已登录，获取用户信息
        user_info = None
        if status["is_logged_in"]:
            account = db.get_active_account()
            if account:
                user_info = {
                    "username": account.get("username", ""),
                    "nickname": account.get("nickname", ""),
                    "avatar_url": account.get("avatar_url", "")
                }
        
        return {
            "success": True,
            "browser_connected": status["browser_connected"],
            "is_logged_in": status["is_logged_in"],
            "message": status["message"],
            "user_info": user_info
        }
    except Exception as e:
        return {
            "success": False,
            "browser_connected": False,
            "is_logged_in": False,
            "message": f"状态检测失败: {str(e)}",
            "user_info": None
        }

@app.post("/api/reconnect-browser")
async def reconnect_browser():
    """重新连接浏览器"""
    try:
        result = toutiao_service.reconnect_browser()
        return result
    except Exception as e:
        return {
            "success": False,
            "message": f"重新连接浏览器失败: {str(e)}"
        }

@app.get("/generate", response_class=HTMLResponse)
async def generate_page(request: Request):
    """文章生成页面"""
    # 获取提示词模板
    templates_data = ai_service.get_suggested_prompts()
    
    return templates.TemplateResponse("generate.html", {
        "request": request,
        "prompt_templates": templates_data
    })

@app.post("/api/generate-article")
async def generate_article(prompt: str = Form(...)):
    """生成文章"""
    try:
        if not prompt.strip():
            raise HTTPException(status_code=400, detail="提示词不能为空")
        
        # 生成文章
        result = ai_service.generate_article(prompt)
        
        if result["success"]:
            # 保存到数据库
            account = db.get_active_account()
            account_id = account["id"] if account else None
            
            article_id = db.save_article(
                title=result["title"],
                content=result["content"],
                prompt=prompt,
                account_id=account_id
            )
            
            return {
                "success": True,
                "article_id": article_id,
                "title": result["title"],
                "content": result["content"]
            }
        else:
            return {
                "success": False,
                "message": result["error"]
            }
            
    except Exception as e:
        return {"success": False, "message": f"生成文章失败: {str(e)}"}

@app.get("/publish", response_class=HTMLResponse)
async def publish_page(request: Request):
    """发布页面"""
    # 获取草稿文章
    account = db.get_active_account()
    if account:
        articles = db.get_articles(account_id=account["id"])
        draft_articles = [a for a in articles if a["status"] == "draft"]
    else:
        draft_articles = []
    
    return templates.TemplateResponse("publish.html", {
        "request": request,
        "articles": draft_articles,
        "account": account
    })

@app.post("/api/publish-article")
async def publish_article(
    article_id: Optional[int] = Form(None),
    title: str = Form(...),
    content: str = Form(...),
    cover_image: Optional[str] = Form(None)
):
    """发布文章"""
    try:
        if not title.strip() or not content.strip():
            raise HTTPException(status_code=400, detail="标题和内容不能为空")
        
        if not cover_image or not cover_image.strip():
            raise HTTPException(status_code=400, detail="封面图片是必需的，请先上传封面图片")
        
        # 发布文章（传入封面图片路径）
        result = toutiao_service.publish_article(title, content, cover_image)
        
        if result["success"]:
            # 更新数据库状态
            if article_id:
                db.update_article_status(
                    article_id, 
                    "published", 
                    result.get("article_url")
                )
            else:
                # 如果是新文章，先保存再更新状态
                account = db.get_active_account()
                account_id = account["id"] if account else None
                new_article_id = db.save_article(title, content, account_id=account_id)
                db.update_article_status(
                    new_article_id, 
                    "published", 
                    result.get("article_url")
                )
            
            return {
                "success": True,
                "message": "文章发布成功",
                "article_url": result.get("article_url")
            }
        else:
            return {
                "success": False,
                "message": result["message"]
            }
            
    except Exception as e:
        return {"success": False, "message": f"发布文章失败: {str(e)}"}

@app.get("/monitor", response_class=HTMLResponse)
async def monitor_page(request: Request):
    """监控页面"""
    account = db.get_active_account()
    
    # 直接从头条官网获取文章数据
    if account:
        try:
            articles = toutiao_service.get_articles_from_website()
        except Exception as e:
            print(f"获取官网数据失败: {str(e)}")
            articles = []
    else:
        articles = []
    
    return templates.TemplateResponse("monitor.html", {
        "request": request,
        "articles": articles,
        "account": account
    })

@app.post("/api/refresh-stats/{article_id}")
async def refresh_article_stats(article_id: int):
    """刷新文章统计数据"""
    try:
        # 这里需要实现获取文章统计的逻辑
        # 由于需要文章URL，这里先返回模拟数据
        stats = {
            "views": 0,
            "likes": 0,
            "comments": 0
        }
        
        return {
            "success": True,
            "stats": stats
        }
        
    except Exception as e:
        return {"success": False, "message": f"刷新统计失败: {str(e)}"}

@app.get("/settings", response_class=HTMLResponse)
async def settings_page(request: Request):
    """设置页面"""
    account = db.get_active_account()
    templates_data = db.get_prompt_templates()
    
    return templates.TemplateResponse("settings.html", {
        "request": request,
        "account": account,
        "templates": templates_data
    })

@app.post("/api/save-template")
async def save_template(
    name: str = Form(...),
    category: str = Form(...),
    prompt: str = Form(...),
    description: str = Form("")
):
    """保存提示词模板"""
    try:
        template_id = db.save_prompt_template(name, category, prompt, description)
        return {
            "success": True,
            "message": "模板保存成功",
            "template_id": template_id
        }
    except Exception as e:
        return {"success": False, "message": f"保存模板失败: {str(e)}"}

@app.post("/api/upload-cover")
async def upload_cover_image(file: UploadFile = File(...)):
    """上传封面图片"""
    try:
        # 检查文件类型
        if not file.content_type.startswith('image/'):
            raise HTTPException(status_code=400, detail="只支持图片文件")
        
        # 生成唯一文件名
        import time
        timestamp = int(time.time())
        file_extension = os.path.splitext(file.filename)[1]
        new_filename = f"cover_{timestamp}{file_extension}"
        
        # 确保上传目录存在
        upload_dir = Config.UPLOAD_DIR
        os.makedirs(upload_dir, exist_ok=True)
        
        # 保存文件
        file_path = os.path.join(upload_dir, new_filename)
        
        with open(file_path, "wb") as buffer:
            content = await file.read()
            buffer.write(content)
        
        return {
            "success": True,
            "message": "图片上传成功",
            "file_path": file_path,
            "filename": new_filename
        }
        
    except Exception as e:
        return {"success": False, "message": f"图片上传失败: {str(e)}"}

@app.post("/api/refresh-stats")
async def refresh_all_stats():
    """刷新所有文章统计数据"""
    try:
        # 直接从头条官网获取最新数据
        articles = toutiao_service.get_articles_from_website()
        
        if not articles:
            return {"success": False, "message": "未获取到文章数据"}
        
        return {
            "success": True,
            "message": "统计数据已更新",
            "articles": articles
        }
        
    except Exception as e:
        return {"success": False, "message": f"获取统计数据失败: {str(e)}"}

@app.post("/api/refresh-stats/{article_index}")
async def refresh_single_article_stats(article_index: int):
    """刷新单个文章统计数据"""
    try:
        # 从头条官网获取所有文章数据
        articles = toutiao_service.get_articles_from_website()
        
        if not articles or article_index >= len(articles):
            return {"success": False, "message": "文章不存在"}
        
        # 返回指定索引的文章数据
        article = articles[article_index]
        
        return {
            "success": True,
            "message": "统计数据已更新",
            "stats": {
                "views": article["views"],
                "likes": article["likes"], 
                "comments": article["comments"],
                "impressions": article["impressions"]
            }
        }
        
    except Exception as e:
        return {"success": False, "message": f"获取统计数据失败: {str(e)}"}

if __name__ == "__main__":
    print("启动头条自动发文系统...")
    print(f"访问地址: http://localhost:8000")
    
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=Config.DEBUG
    )
